import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/lifeCircle/services/follow_status_sync_service.dart';
import 'package:casdon/modules/me/application/notification/flower_list_notifier.dart';
import 'package:casdon/modules/me/data/api/flower_list_api.dart';
import 'package:casdon/modules/me/data/repository/me_repository_impl.dart';
import 'package:casdon/modules/me/ui/widgets/circle_avatar_button.dart';
import 'package:casdon/auto_router.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class FlowerListScreen extends ConsumerStatefulWidget {
  const FlowerListScreen({super.key});

  @override
  ConsumerState<FlowerListScreen> createState() => _FlowerListState();
}

class _FlowerListState extends ConsumerState<FlowerListScreen> {
  @override
  void initState() {
    super.initState();
    // 每次进入页面时，确保刷新数据
    // 使用 Future.microtask 确保 ref 可用
    Future.microtask(() {
      if (mounted) {
        ref.invalidate(flowerListNotifierProvider);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(flowerListNotifierProvider);
    final notifier = ref.read(flowerListNotifierProvider.notifier);

    return Scaffold(
      backgroundColor: context.colorScheme.surface,
      appBar: CommonAppBar(title: "关注"),
      body: SafeArea(
        child: RefreshIndicator(
          onRefresh: () => notifier.refresh(),
          child: NotificationListener<ScrollNotification>(
            onNotification: (notification) {
              if (notification is ScrollEndNotification &&
                  notification.metrics.pixels >=
                      notification.metrics.maxScrollExtent - 50) {
                notifier.loadMore();
              }
              return false;
            },
            child: state.when(
              loading: () => const Center(child: CommonLoadingWidget()),
              error: (error, stack) => Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text('加载失败'),
                    SizedBox(height: 16.h),
                    ElevatedButton(
                      onPressed: () => notifier.refresh(),
                      child: const Text('重试'),
                    ),
                  ],
                ),
              ),
              data: (state) {
                if (state.data.isEmpty) {
                  return ListView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    children: [
                      SizedBox(
                        height:
                            MediaQuery.of(context).size.height -
                            MediaQuery.of(context).padding.top -
                            60.h, // AppBar 高度
                        child: _buildEmptyState(),
                      ),
                    ],
                  );
                }

                return ListView.builder(
                  padding: EdgeInsets.only(top: 10.h),
                  itemCount: state.data.length + (state.hasMore ? 1 : 0),
                  itemBuilder: (context, index) {
                    // 显示加载更多指示器
                    if (index == state.data.length) {
                      return _buildLoadMoreIndicator(state.isLoadingMore);
                    }
                    final flower = state.data[index];
                    return _buildFlowerItem(flower);
                  },
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLoadMoreIndicator(bool isLoading) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.h),
      alignment: Alignment.center,
      child: isLoading
          ? const CircularProgressIndicator()
          : const SizedBox.shrink(),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image(
            image: Assets.images.emptyData.provider(),
            width: 106.w,
            height: 68.w,
          ),
          SizedBox(height: 16.h),
          Text(
            "暂无数据",
            style: context.textTheme.bodyMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFlowerItem(Flower flower) {
    final isFollowed = flower.isFollow ?? false;

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 22.w),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            color:
                context.customColorThemeNonNull.gray1 ?? Colors.grey.shade200,
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: () {
                _handleUserTap(flower);
              },
              behavior: HitTestBehavior.opaque,
              child: Row(
                children: [
                  CircleAvatarButton(
                    imageUrl: flower.followUserAvatars ?? "",
                    defaultImage: AssetImage(Assets.images.icAvatar.path),
                    size: 36.w,
                    onPressed: () {
                      _handleUserTap(flower);
                    },
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Text(
                      flower.followUserNickname ?? "匿名用户",
                      style: context.textTheme.headlineMedium!.copyWith(
                        color: context.customColorThemeNonNull.textColor1,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(width: 12.w),
          _buildFollowButton(flower, isFollowed),
        ],
      ),
    );
  }

  Widget _buildFollowButton(Flower flower, bool isFollowed) {
    return GestureDetector(
      onTap: () => _handleFollowTap(flower, isFollowed),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: isFollowed ? Colors.white : Colors.white,
          borderRadius: BorderRadius.circular(24.r),
          border: Border.all(
            color: isFollowed
                ? context.customColorThemeNonNull.gray2!
                : context.colorScheme.primary,
            width: 1,
          ),
        ),
        child: Text(
          isFollowed ? "已关注" : "关注",
          style: context.textTheme.bodyMedium!.copyWith(
            color: isFollowed
                ? context.customColorThemeNonNull.textColor3
                : context.colorScheme.primary,
            fontWeight: isFollowed ? FontWeight.w400 : FontWeight.w600,
          ),
        ),
      ),
    );
  }

  Future<void> _handleFollowTap(Flower flower, bool isFollowed) async {
    try {
      final repository = MeRepositoryImpl(
        apiClient: ref.read(apiClientProvider),
      );
      final newFollowStatus = !isFollowed;

      await repository.followUser(
        followUuid: flower.followUuid,
        flag: isFollowed ? "0" : "1", // "1"：关注，"0"：取消关注
      );
      if (isFollowed == false) {
        ToastUtil.show("关注成功");
      } else {
        ToastUtil.show("取消关注成功");
      }
      // 使用统一的同步服务更新所有相关列表的状态
      final syncService = FollowStatusSyncService(ref);
      syncService.syncFollowStatus(flower.followUuid, newFollowStatus);
    } on DioException catch (e) {
      if (!context.mounted) return;
    } catch (e) {
      // 处理错误，可以显示 Toast
      debugPrint("关注操作失败: $e");
    }
  }

  void _handleUserTap(Flower flower) {
    LifeUserHomeRoute(
      userId: flower.followUuid,
      nickName: flower.followUserNickname,
      avatar: flower.followUserAvatars,
    ).push(context);
  }
}
